<?php

namespace App\Http\Controllers\Innerend;


use App\Models\Admin;
use App\Models\ArticleComment;
use App\Models\Dispatch;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class DispatchController extends BaseController
{
    // 快讯
    public function initialize()
    {
        parent::initialize();

        $this->model = 'Dispatch';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $users  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_uid  = $item['uid'];
            $_user = $users[$_uid] ?? [];
            $_id   = $item['id'];
            //$status   = $item['status'] == 1 ? '正常' : '禁用';
            $majorOp  = $item['is_major'] == 1 ? '设为不重要' : '设为重要';
            $is_major = $item['is_major'] == 1 ? '是' : '否';
            // 操作
            $operate = $listHtml->operate_status(['id' => $_id, 'is_major' => 1 - $item['is_major']], $majorOp, $item['is_major'], 'set-major');
            $operate .= $listHtml->operate_edit(['id' => $_id], '编辑快讯');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该快讯吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($_user['username']);
            $tr .= $listHtml->list_td($item['title']);
            $tr .= $listHtml->list_td($item['content']);
            $tr .= $listHtml->list_td($is_major);
            //$tr .= $listHtml->list_td($status);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        // 'role' => '角色',
        return ['uid' => ['用户', 80], 'title' => ['标题', 250], 'content' => '内容', 'is_major' => ['重要性', 40], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }


    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();

        // 用户名
        //$role     = $form->formCheckbox('role', json_decode($info['role']), $all); // 角色
        $username = $form->formInput('username', $info['username'] ?? '', '用户名');
        $username = $form->formInput('uid', $info['uid'] ?? '', '用户名');

        $username = $form->ajaxSearch('uid', $info['uid'] ?? '', 'User');
        $is_major = $form->formRadio('is_major', $info['is_major'] ?? 1, [1 => '重要', 0 => '不重要']);
        $title    = $form->formInput('title', $info['title'] ?? '', '标题');
        $content  = $form->formTextarea('content', $info['content'] ?? '');
        $_id      = $form->formHidden('id', $info['id'] ?? '');

        $html .= $form->makeItem('编辑', $username);
        $html .= $form->makeItem('重要性', $is_major);
        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('内容', $content);
        $html .= $_id;

        return $html;
    }


    // 删除（软删除）
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 删除（软删除）
    public function delComment()
    {
        $ids = $this->getData('ids', [], 'is_array');
        $this->throwIf(empty($ids), '请指定删除记录!');
        $this->throwIf(count($ids) != count($ids, 1), '指定删除记录参数错误!');
        // 其他条件
        $dis_id = $this->getData('dispatch_id', 0, 'intval');
        $where  = ['channel' => 'news', 'article_id' => $dis_id];
        $this->throwIf(empty($dis_id), '请指定快讯编号!');


        $comment = new ArticleComment();
        $result  = $comment->isCache(true)->softDelete($where, $ids);
        $this->throwIf($result === false, $comment->getError());

        return $this->success();
    }

    // 查找
    public function show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id], ['verify', '=', 1]];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        // 查找用户信息
        if($info['uid']){
            $uid    = $info['uid'];
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            if($user){
                // $user               = $user[$uid];
                // 整理
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
            }
            $info['user'] = $user;
        }

        return $this->success($info);
    }

    // 快讯的评论
    public function comment()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');
        $where   = ['article_id' => $this->id, 'channel' => 'dispatch', 'verify' => 1]; // 'pid' => 0,
        $comment = new ArticleComment();
        $result  = $comment->listPage($where, $this->page, $this->rows);
        if($result['list']){
            $uids   = array_column($result['list'], 'uid');
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            $users  = $userDb->isCache(true)->getListInIds($uids);
            foreach($result['list'] as $key => $item){
                $_uid  = $item['uid'];
                $_info = $users[$_uid] ?? [];
                if($_info){
                    $_info['head_img']   = $this->getHeadImg($_info['head_img'] ?? '');
                    $_info['apply_type'] = $_info['is_apply'] == 1 ? ($types[$_info['apply_type']]['name'] ?? '') : '';
                    // $_info['apply_type'] = $types[$_info['apply_type']]['name'] ?? '';
                }

                // 整理
                $result['list'][$key]['user'] = $_info;
            }
        }

        return $this->success($result);
    }

    // 设置标红（终于）
    public function setMajor()
    {
        $_value = $this->getData('is_major', 0, 'intval');
        $ids    = $this->getData("ids", [], 'is_array');
        $id     = $this->id;
        $this->throwIf(!in_array($_value, [0, 1]), '是否标红状态必须为0或1！');
        $this->throwReturn(empty($ids) && empty($id), '请选择需要修改的数据！');
        $this->throwReturn(count($ids) != count($ids, 1), '请选择正确id数据！');

        // 组合
        if($id){
            $ids[] = $id;
        }

        // 查询数据
        $model = new Dispatch();
        $lists = $model->isCache(true)->getListInIds($ids);
        if(empty($lists)){
            return $this->error('你要操作的数据不存在！！');
        }

        $_ids = array_column($lists, 'id');
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $model->whereIn('id', $_ids)->update(['is_major' => $_value]);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->error($e->getMessage());
        }

        // 缓存操作
        $model->deleteCacheList($lists);
        $model->deleteCacheShow(['id' => $_ids, 'is_major' => $_value]);

        return $this->success();
    }


    // 列表查询
    protected function listWhere()
    {
        $where   = [['verify', '=', 1]];
        $keyword = $this->getData('keyword', null, 'trim');
        if($keyword){
            $where[] = ['content', 'like', "%$keyword%"];
            // 缓存设置
            $this->listCache = false;
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            // 'comment_no' => $this->getData("comment_no", 0, 'intval'),
            // 'collect_no' => $this->getData("collect_no", 0, 'intval'),
            // 'praise_no'  => $this->getData("praise_no", 0, 'intval'),
            // 'stamp_no'   => $this->getData("stamp_no", 0, 'intval'),
            // 'relay_no'   => $this->getData("relay_no", 0, 'intval'),
            // 'verify'     => $this->getData("verify", 0, 'intval'),

            'news_id'   => $this->getData("news_id", 0, 'intval'),
            'uid'       => $this->getData("uid", 1, 'intval'),  // 默认用户 1
            'origin_id' => $this->getData("origin_id", 0, 'intval'),
            'is_major'  => $this->getData("is_major", 0, 'intval'),
            'keywords'  => $this->getData("keywords", null, 'trim'),
            'title'     => $this->getData("title", null, 'trim'),
            'content'   => $this->getData("content", null, 'trim'),
            'verify'    => 1,
        ];

        $this->throwIf(empty($data['uid']), '请选择发布的用户!');
        // TODO 审核
        $this->baiduTextCensor($data);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'news_id'   => $this->getData("news_id", 0, 'intval'),
            'uid'       => $this->getData("uid", 1, 'intval'),  // 默认用户 1
            'origin_id' => $this->getData("origin_id", 0, 'intval'),
            'is_major'  => $this->getData("is_major", 0, 'intval'),
            'keywords'  => $this->getData("keywords", null, 'trim'),
            'title'     => $this->getData("title", null, 'trim'),
            'content'   => $this->getData("content", null, 'trim'),
            'verify'    => 1,
        ];

        $this->throwIf(empty($data['uid']), '请选择发布的用户!');
        // TODO 审核
        $this->baiduTextCensor($data);

        return $data;
    }

}


